package com.test.demo.weight

import android.graphics.*
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest

/**
 * @projectName
 * @author
 * @description:　圆角
 * @date : 2024/11/15 17:13
 * @version 1.0.0
 */
class CustomRoundedCornersTransformation(
    private val topLeftRadius: Float? = 0.0f,
    private val topRightRadius: Float? = 0.0f,
    private val bottomLeftRadius: Float? = 0.0f,
    private val bottomRightRadius: Float? = 0.0f
) : BitmapTransformation() {

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update("CustomRoundedCornersTransformation".toByteArray())
    }

    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap {
        return roundCorners(pool, toTransform)
    }

    private fun roundCorners(pool: BitmapPool, source: Bitmap): Bitmap {
        val width = source.width
        val height = source.height

        val bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        val paint = Paint()
        paint.isAntiAlias = true
        paint.shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)

        val path = Path()
        val radii = floatArrayOf(
            topLeftRadius ?: 0f, topLeftRadius ?: 0f,    // Top left
            topRightRadius ?: 0f, topRightRadius ?: 0f, // Top right
            bottomRightRadius ?: 0f, bottomRightRadius ?: 0f, // Bottom right
            bottomLeftRadius ?: 0f, bottomLeftRadius ?: 0f // Bottom left
        )
        path.addRoundRect(
            RectF(0f, 0f, width.toFloat(), height.toFloat()),
            radii,
            Path.Direction.CW
        )
        canvas.drawPath(path, paint)
        return bitmap
    }

}